package com.tiantian.quanminxiu.utils;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.hardware.Camera;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.TrafficStats;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.telephony.TelephonyManager;
import android.view.View;
import android.widget.ImageView;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.shenglian.utils.utils.CommonUtils;
import com.shenglian.utils.utils.ImageUtils;
import com.tiantian.quanminxiu.activity.Activity_Authentication;
import com.tiantian.quanminxiu.activity.Activity_Register;
import com.tiantian.quanminxiu.activity.Activity_Search;
import com.tiantian.quanminxiu.activity.Activity_Sina;
import com.tiantian.quanminxiu.dialog.Dialog_NotLive;
import com.tiantian.quanminxiu.dialog.Dialog_Share;
import com.tiantian.quanminxiu.dialog.Dialog_StartLive;
import com.tiantian.quanminxiu.dialog.Dialog_UploadPicture;
import com.tiantian.quanminxiu.view.PhoneLookView;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.tiantian.quanminxiu.R;
import com.tiantian.quanminxiu.activity.Activity_EditInfo;
import com.tiantian.quanminxiu.activity.Activity_FanRoll;
import com.tiantian.quanminxiu.activity.Activity_Login;
import com.tiantian.quanminxiu.activity.Activity_LoginSelect;
import com.tiantian.quanminxiu.activity.Activity_PhoneLive;
import com.tiantian.quanminxiu.activity.Activity_PhoneLook;
import com.tiantian.quanminxiu.activity.Activity_QQLoginHelper;
import com.tiantian.quanminxiu.activity.Activity_Recharge;
import com.tiantian.quanminxiu.activity.Activity_Signature;
import com.tiantian.quanminxiu.activity.MainActivity;
import com.tiantian.quanminxiu.dialog.Dialog_GiftList;
import com.tiantian.quanminxiu.dialog.Dialog_GiftRecord;
import com.tiantian.quanminxiu.dialog.Dialog_OpenGuard;
import com.tiantian.quanminxiu.dialog.Dialog_UploadingPhoto;
import com.tiantian.quanminxiu.dialog.Dialog_UserInfoCard;
import com.tiantian.quanminxiu.dialog.Dialog_UserList;

import java.io.File;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import rx.functions.Action1;

/**
 * Created by admin on 2015/12/2.
 */
public class APPUtils {

    /* SharedPreferences 文件名 */
    public static final String APP_SHARENAME = ApplicationBase.class.getName() + ".APP_SHARENAME";
    /* 是否第一次本手机登陆 */
    public static final String IS_FIRSTSTART = ApplicationBase.class.getName() + ".IS_FIRSTSTART";

    //region 判断App是否退出的操作逻辑 APPExit（Activity context）
    // 按两次返回键退出
    private static long longExitTime;

    public static void APPExit(Activity context) {
        if ((System.currentTimeMillis() - longExitTime) <= 2000) {
            try {
                context.finish();
                return;
            } catch (Exception e) {
                android.os.Process.killProcess(android.os.Process.myPid());
            }
        }
        CommonUtils.showToask(context, "再按一次退出" + context.getResources().getString(R.string.app_name));
        longExitTime = System.currentTimeMillis();
    }
    //endregion

    //region 第三方分享 ShareAppUtils(Activity activity,String anchor,int roomId,UMShareListener backcall)
    public static Dialog_Share ShareAppUtils(Activity activity, String anchor, int roomId, String title){
        Dialog_Share dialog = new Dialog_Share(activity,R.style.DialogStyleCustom,roomId,anchor,title);
        dialog.show();
        return dialog;
    }
    //endregion

    //region 第三方分享 ShareAppUtils(Activity activity,String anchor,int roomId,UMShareListener backcall)
    public static void ShareAppUtils(Activity activity,String anchor,int roomId,UMShareListener backcall){
        new ShareAction(activity).setDisplayList(SHARE_MEDIA.SINA,SHARE_MEDIA.QQ,SHARE_MEDIA.QZONE,SHARE_MEDIA.WEIXIN,SHARE_MEDIA.WEIXIN_CIRCLE)
                .withTitle(anchor+"正在直播(房间ID:"+roomId+")")
                .withText("hi,("+anchor+")正在全民秀直播@才艺表演，快来一起互动吧～")
                .withMedia(new UMImage(activity, "http://utils.quanminxiu.tv/service/img/user/cover/" + roomId + "/480.360.jpg"))
                .withTargetUrl(ApplicationBase.downAppUrl)
                .setCallback(backcall)
                .open();
    }
    //endregion

    //region 第三方授权 LoginAuthUtils(Activity activity,SHARE_MEDIA platform,UMAuthListener backcall)
    public static void LoginAuthUtils(Activity activity,UMShareAPI mShareAPI,SHARE_MEDIA platform,UMAuthListener backcall){
        mShareAPI.doOauthVerify(activity, platform, backcall);
    }
    //endregion
    //region 第三方登录 LoginAppUtils(Activity activity,SHARE_MEDIA platform,UMAuthListener backcall)
    public static void LoginAppUtils(Activity activity,UMShareAPI mShareAPI,SHARE_MEDIA platform,UMAuthListener backcall){
        mShareAPI.getPlatformInfo(activity, platform, backcall);
    }
    //endregion


    //region 转到qq登录分享页面 QQHelperLogin_To(Activity activity)
    public static void QQHelperLogin_To(Activity activity) {
        QQHelperLogin_To(activity,0,0,"","");
    }
    public static void QQHelperLogin_To(Activity activity,int isLogin,int roomId,String anchorName,String title) {
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra("isLogin", isLogin);
        intent.putExtra("roomId", roomId);
        intent.putExtra("anchorName", anchorName);
        intent.putExtra("title", title);
        intent.setClass(activity.getBaseContext(), Activity_QQLoginHelper.class);
        activity.startActivity(intent);
    }
    //endregion

    //region 转到微博登录分享页面 SinaLogin_To(Activity activity)
    public static void SinaLogin_To(Activity activity) {
        SinaShare_To(activity,0,0,"","title");
    }
    public static void SinaShare_To(Activity activity,int isLogin,int roomId,String anchorName,String title) {
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra("isLogin", isLogin);
        intent.putExtra("roomId", roomId);
        intent.putExtra("anchorName", anchorName);
        intent.putExtra("title", title);
        intent.setClass(activity.getBaseContext(), Activity_Sina.class);
        activity.startActivity(intent);
    }
    //endregion


    //region 转到开播窗口  StartLive_To(Activity activity, String NickName,int UserId)
    public static void StartLive_To(Activity activity, String NickName,int UserId) {
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra("NickName", NickName);
        intent.putExtra("Anchor_id", UserId);
        intent.setClass(activity, Dialog_StartLive.class);
        activity.startActivity(intent);
    }
    //endregion

    //region 弹出礼物列表窗口 Dialog_GiftList_To(Activity activity,View view)
    public static Dialog_GiftList Dialog_GiftList_To(Activity activity,View view,int anchor_id,String anchor_name) {
        Dialog_GiftList dialog_giftList = Dialog_GiftList.getInstance(activity,anchor_id,anchor_name);
        dialog_giftList.show(view);
        return dialog_giftList;
    }
    //endregion

    //region 弹出用户卡片窗口 Dialog_UserInfoCard_To(Activity activity,int UserId,String NickName,int fan,int level,int anchorlevel,boolean attention,boolean isLive) {
    public static Dialog_UserInfoCard Dialog_UserInfoCard_To(Activity activity,int UserId,String NickName,int fan,int level,int anchorlevel,boolean attention) {
        return Dialog_UserInfoCard_To(activity,UserId,NickName,fan,level,anchorlevel,attention,true);
    }
    public static Dialog_UserInfoCard Dialog_UserInfoCard_To(Activity activity,int UserId,String NickName,int fan,int level,int anchorlevel,boolean attention,boolean isLive) {
        Dialog_UserInfoCard dialog = new Dialog_UserInfoCard(activity,R.style.DialogStyleCustom,UserId,NickName,fan,level,anchorlevel,attention,isLive);
        dialog.show();
        return dialog;
    }
    //endregion

    //region 弹出开通守护窗口 Dialog_OpenGuard_To(Activity activity,int UserId,String NickName)
    public static Dialog_OpenGuard Dialog_OpenGuard_To(Activity activity,String UserId,String NickName) {
        Dialog_OpenGuard dialog = new Dialog_OpenGuard(activity,R.style.DialogStyleCustom,UserId,NickName);
        dialog.show();
        return dialog;
    }
    //endregion

    //region 弹出礼物记录窗口 Dialog_OpenGuard_To(Activity activity,String anchor_id,View view)
    public static Dialog_GiftRecord Dialog_GiftRecord_To(Activity activity,String anchor_id,View view) {
        Dialog_GiftRecord dialog = Dialog_GiftRecord.getInstance(activity,anchor_id);
        dialog.show(view);
        return dialog;
    }
    //endregion

    //region 弹出主播未开播窗口 Dialog_NotLive_TO(Activity activity, int roomId,PhoneLookView phoneLookView)
    public static Dialog_NotLive Dialog_NotLive_TO(Activity activity, PhoneLookView phoneLookView) {
        Dialog_NotLive dialog = new Dialog_NotLive(activity,R.style.DialogStyleCustom,phoneLookView);
        dialog.show();
        return dialog;
    }
    //endregion
    //region 弹出管理员列表窗口 Dialog_OpenGuard_To(Activity activity,String anchor_id,View view)
    public static Dialog_UserList Dialog_UserList_To(Activity activity,String anchor_id,View view) {
        Dialog_UserList dialog = Dialog_UserList.getInstance(activity,anchor_id);
        dialog.show(view);
        return dialog;
    }
    //endregion

    //region 转到首页页面 Main_To(Activity activity,int roomId)
    public static void Main_To(Activity activity) {
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.setClass(activity.getBaseContext(), MainActivity.class);
        activity.startActivity(intent);
    }
    //endregion

    //region 转到登录页面 Login_To(Activity activity)
    public static void Login_To(Activity activity) {
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.setClass(activity.getBaseContext(), Activity_Login.class);
        activity.startActivity(intent);
    }
    //endregion

    //region 转到登录选择页面 LoginSelect_To(Activity activity)
    public static void LoginSelect_To(Activity activity) {
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.setClass(activity.getBaseContext(), Activity_LoginSelect.class);
        activity.startActivity(intent);
    }
    //endregion

    //region 跳转到注册界面 Register_To(Activity activity)
    public static void Register_To(Activity activity){
        Intent intent = new Intent();
        intent.setClass(activity.getBaseContext(), Activity_Register.class);
        activity.startActivity(intent);
    }
    //endregion

    //region 转到用户编辑页面 EditInfo_TO(Activity activity)
    public static void EditInfo_TO(Activity activity) {
        Intent intent = new Intent(activity, Activity_EditInfo.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        activity.startActivity(intent);
    }
    //endregion

    //region 转到主播认证页面 Authentication_TO(Activity activity)
    public static void Authentication_TO(Activity activity) {
        Intent intent = new Intent(activity, Activity_Authentication.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        activity.startActivity(intent);
    }
    //endregion

    //region 转到搜索页面 EditInfo_TO(Activity activity)
    public static void Search_TO(Activity activity) {
        Intent intent = new Intent(activity, Activity_Search.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        activity.startActivity(intent);
    }
    //endregion

    //region 转到用户签名页面 Signature_TO(Activity activity)
    public static void Signature_TO(Activity activity,int requestCode) {
        Intent intent = new Intent(activity, Activity_Signature.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        activity.startActivityForResult(intent, requestCode);
    }
    //endregion

    //region 转到充值页面 Recharge_TO(Activity activity)
    public static void Recharge_TO(Activity activity) {
        Intent intent = new Intent(activity, Activity_Recharge.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        activity.startActivity(intent);
    }
    //endregion

    //region 转到充值页面 Recharge_TO(Activity activity)
    public static void Recharge_TO(Activity activity,boolean isGiftList) {
        Intent intent = new Intent(activity, Activity_Recharge.class);
        intent.putExtra("isGiftList",isGiftList);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        activity.startActivity(intent);
    }
    //endregion

    //region 转到观看直播页面 PhoneLook_To(Activity activity,int RoomId)
    public static void PhoneLook_To(Activity activity,int RoomId) {
        Intent intent = new Intent(activity, Activity_PhoneLook.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra("sign", UserData.Current.sign);
        intent.putExtra("mid", UserData.Current.mid);
        intent.putExtra("RoomId", RoomId);
        activity.startActivity(intent);
    }
    //endregion

    //region 转到开始直播页面 PhoneLook_To(Activity activity,int RoomId)
    public static void PhoneLive_To(Activity activity,int RoomId) {
        if(!UserData.Base.isAnchor){
            CommonUtils.showToask(activity,"你还不是艺人..");
            return;
        }
        Intent intent = new Intent(activity, Activity_PhoneLive.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra("sign", UserData.Current.sign);
        intent.putExtra("mid", UserData.Current.mid);
        intent.putExtra("RoomId", RoomId);
        activity.startActivity(intent);
    }
    //endregion

    //region 转到粉丝榜页面 FanRoll_To(Activity activity,int roomId)
    public static void FanRoll_To(Activity activity,int roomId,String NickName) {
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra("roomId", roomId);
        intent.putExtra("NickName", NickName);
        intent.setClass(activity.getBaseContext(), Activity_FanRoll.class);
        activity.startActivity(intent);
    }
    //endregion

    //region 转到上传图片界面  UploadPhoto_To(Activity activity, String url, String key, int id) *key 是上传参数名称 *id 是上传参数id *url上传网络地址
    public static void UploadPhoto_To(Activity activity, String url, String key, int id) {
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra("url", url);
        intent.putExtra("key", key);
        intent.putExtra(key, id);
        intent.setClass(activity, Dialog_UploadingPhoto.class);
        activity.startActivity(intent);
    }
    //endregion

    //region 转到上传图片界面  UploadPhoto_To(Activity activity, String url, String key, int id) *key 是上传参数名称 *id 是上传参数id *url上传网络地址
    public static void UploadPictur_To(Activity activity,int requestCode) {
        UploadPictur_To(activity,requestCode,true);
    }

    public static void UploadPictur_To(Activity activity,int requestCode,boolean isCutPicture) {
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra("isCutPicture",isCutPicture);
        intent.setClass(activity, Dialog_UploadPicture.class);
        activity.startActivityForResult(intent,requestCode);
    }
    //endregion

    //region 拨打电话 CallPhone(Context context, String Number)
    public static void CallPhone(Context context, String Number) {
        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + Number));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }
    //endregion

    //region 拨打电话点击事件 CallPhone_OnClickListener
    public static Action1<View> CallPhone_OnClickListener = v -> {
        if (v.getTag() == null) {
            return;
        }
        CallPhone(v.getContext(), v.getTag().toString());
    };
    //endregion

    //region 调用到系统相册界面 SystemPhoto_To(Activity activity)
    public static void SystemPhoto_To(Activity activity) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            activity.startActivityForResult(Intent.createChooser(intent, "请选图片"), CommonEnum.RequestCode.System_Photo);
        } else {
            Intent intent = new Intent("android.intent.action.GET_CONTENT");
            intent.setType("image/*");
            activity.startActivityForResult(intent, CommonEnum.RequestCode.System_Photo_KITKAT); // 打开相册
        }
    }
    //endregion

    //region 调用系统相机界面 SystemCamera_To(Activity activity, String localCameraPath)
    public static void SystemCamera_To(Activity activity, String localCameraPath) {
        Intent takePictureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
        Uri imageUri = Uri.fromFile(new File(localCameraPath));
        takePictureIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, imageUri);
        if (takePictureIntent.resolveActivity(activity.getPackageManager()) != null) {
            activity.startActivityForResult(takePictureIntent, CommonEnum.RequestCode.System_Camera);
        }
    }
    //endregion


    // region 调用系统相机界面 SystemCamera_To(Activity activity, File localCameraPath)
    public static void SystemCamera_To(Activity activity, File localCameraPath) {
        Intent takePictureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
        Uri imageUri = Uri.fromFile(localCameraPath);
        takePictureIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, imageUri);
        if (takePictureIntent.resolveActivity(activity.getPackageManager()) != null) {
            activity.startActivityForResult(takePictureIntent, CommonEnum.RequestCode.System_Camera);
        }
    }
    //endregion

    //region 判断网络，并弹出提示 Network_Check_Toast(Context context)
    public static boolean Network_Check_Toask(Context context) {
        if (!CommonUtils.checkNetState(context)) {
            Network_Tips_Toask(context);
            return false;
        }
        return true;
    }
    //endregion

    //region 网络提示(文字型) Network_Tips_Toask(Context context)
    public static void Network_Tips_Toask(Context context) {
        CommonUtils.showToask(context, "当前网络较慢，请稍后重试...");
    }
    //endregion

    //region 加载图片 displayImage() url：地址 imageView:加载图片 IsCache:是否需要缓存,hasAnim是否有动画, content:上下文 angle:圆角度数
    private static DisplayImageOptions options = null;

    public static void displayImage(String uri, ImageView imageView, boolean IsCache, boolean hasAnim,Context context, int angle) {
        if (!IsCache) {
            if (angle > 0 && context != null) {
                ImageLoader.getInstance().displayImage(uri, imageView, new DisplayImageOptions.Builder().displayer(new RoundedBitmapDisplayer(CommonUtils.dip2px(context, angle))).build());
            } else if(!hasAnim){
                ImageLoader.getInstance().displayImage(uri, imageView,new DisplayImageOptions.Builder().build());
            }else{
                ImageLoader.getInstance().displayImage(uri, imageView);
            }
        } else {
            if (angle > 0 && context != null) {
                ImageLoader.getInstance().displayImage(uri, imageView, new DisplayImageOptions.Builder()
                        .showImageForEmptyUri(R.drawable.chat_common_empty_photo)
                        .showImageOnFail(R.drawable.chat_common_empty_photo)
                        .cacheInMemory(true)
                        .cacheOnDisk(true)
                        .considerExifParams(true)
                        .displayer(new RoundedBitmapDisplayer(CommonUtils.dip2px(context, angle)))
                        .build());
            } else {
                if (options == null) {
                    options = new DisplayImageOptions.Builder()
                            .showImageForEmptyUri(R.drawable.chat_common_empty_photo)
                            .showImageOnFail(R.drawable.chat_common_empty_photo)
                            .cacheInMemory(true)
                            .cacheOnDisk(true)
                            .considerExifParams(true)
                            .displayer(new FadeInBitmapDisplayer(200))
                            .build();
                }
                ImageLoader.getInstance().displayImage(uri, imageView, options);
            }
        }
    }

    public static void displayImage(String uri, ImageView imageView) {
        displayImage(uri, imageView, false,true, null, -1);
    }

    public static void displayImage(String uri, ImageView imageView, boolean IsCache) {
        displayImage(uri, imageView, IsCache,true, null, -1);
    }

    public static void displayImage(String uri, ImageView imageView, Context context, int angle) {
        displayImage(uri, imageView, false,true, context, angle);
    }

    public static void displayImage(String uri, ImageView imageView, boolean IsCache,boolean hasAnim) {
        displayImage(uri, imageView, IsCache,hasAnim, null, -1);
    }

    public static void displayImage(String uri, ImageView imageView, boolean IsCache,Context context, int angle) {
        displayImage(uri, imageView, IsCache,true, context, angle);
    }
    //endregion

    //region 判断摄像机是否可用 isCameraCanUse
    public static boolean isCameraCanUse() {
        boolean canUse = true;
        Camera mCamera = null;
        try {
            mCamera = Camera.open();
        } catch (Exception e) {
            canUse = false;
        }
        if (canUse) {
            try {
                mCamera.release();
                mCamera = null;
            } catch (Exception e) {
                mCamera = null;
                canUse = false;
            }
        }
        return canUse;
    }
    //endregion

    //region 判断并生成主播头像图片 createUserAvatar
    public static String createUserAvatar(int UserId) {
        String drawable;
        if(!UserData.Current.USERAVATAR_URL.isEmpty()){
            drawable = UserData.Current.USERAVATAR_URL+UserId+"/80.80.jpg";
        }else {
            drawable = Constants.USERAVATAR_URL+UserId+"/80.80.jpg";
        }
        return drawable;
    }
    //endregion

    //region 判断并生成主播封面图片 createUserCover
    public static String createUserCover(int UserId) {
        String drawable;
       if(!UserData.Current.USERCOVER_URL.isEmpty()){
            drawable = UserData.Current.USERCOVER_URL+UserId+"/294.294.jpg";
        }else {
            drawable = Constants.USERCOVER_URL+UserId+"/294.294.jpg";
        }
        return drawable;
    }
    //endregion

    //region 判断并生成礼物图片 createGiftImg
    public static String createGiftImg(int giftid) {
        String drawable = Constants.GIFTPIC_URL+giftid+".png";
        return drawable;
    }
    //endregion

    //region 得到等级图片 getLevelPic(Activity activity,int level)
    public static int getLevelPic(Context context,int level){
        int faceId = 0;
        if(level>=0 &&level<37){
            faceId = context.getResources().getIdentifier("icon_level_" + level, "drawable", context.getPackageName());
        }
        return faceId;
    }
    //endregion

    //region 得到等级图片 getAnchorLevelPic(Activity activity,int level)
    public static int getAnchorLevelPic(Activity activity,int level){
        int faceId = 0;
        if(level>0 &&level<31){
            faceId = activity.getResources().getIdentifier("icon_anchor_" + level, "drawable", activity.getPackageName());
        }
        return faceId;
    }
    //endregion

    //region 高版本获取资源 getResourcesDrawble getResourcesColor
    public static Drawable getResourcesDrawble(Context context,int drawable){
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1) {
            return context.getDrawable(drawable);
        }else {
            return context.getResources().getDrawable(drawable);
        }
    };
    public static int getResourcesColor(Context context,int color){
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1) {
            return context.getColor(color);
        }else {
            return context.getResources().getColor(color);
        }
    };
    //endregion

    //region 创建平铺图片 createRepeater(Context context,int width, int drawable,int srcsize)
    public static Bitmap createRepeater(Context context, int width, int height, int drawable, int srcsize) {
        Bitmap src = BitmapFactory.decodeResource(context.getResources(), drawable);

        //缩小到指定图片
        float oldwidth = src.getWidth();
        float oldheight = src.getHeight();
        // 创建操作图片用的matrix对象
        Matrix matrix = new Matrix();
        // 计算宽高缩放率
        float scaleWidth = ((float) srcsize) / oldwidth;
        float scaleHeight = ((float) srcsize) / oldheight;
        // 缩放图片动作
        matrix.postScale(scaleWidth, scaleHeight);
        src = Bitmap.createBitmap(src, 0, 0, (int) oldwidth,
                (int) oldheight, matrix, true);

        //平铺图片
        int widthcount = width / src.getWidth() + 1;
        int heacount = height / src.getHeight() + 1;
        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);

        for (int idy = 0; idy < heacount; ++idy) {
            for (int idx = 0; idx < widthcount; ++idx) {
                canvas.drawBitmap(src, idx * src.getWidth(), idy * src.getHeight(), null);
            }
        }
        return bitmap;
    }
    //endregion

    //region 模糊图片处理 doFastBlur(Context context,View view,int drawable,int width,int height)
    public static void doFastBlur(Context context, View view, int drawable) {

        Bitmap src = BitmapFactory.decodeResource(context.getResources(), drawable);

        //图片不能铺满整个屏幕，需要调整图片大小
        src = Zoom(src, view.getMeasuredWidth(), view.getMeasuredHeight());

        float scaleFactor = 8;
        float radius = 4;

        //压缩图片
        Bitmap overlay = Bitmap.createBitmap(
                (int) (view.getMeasuredWidth() / scaleFactor),
                (int) (view.getMeasuredHeight() / scaleFactor),
                Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(overlay);
        canvas.translate(-view.getLeft() / scaleFactor, -view.getTop()
                / scaleFactor);
        canvas.scale(1 / scaleFactor, 1 / scaleFactor);
        Paint paint = new Paint();
        paint.setFlags(Paint.FILTER_BITMAP_FLAG);
        canvas.drawBitmap(src, 0, 0, paint);

        overlay = ImageUtils.doFastBlur(overlay, (int) radius, true);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            //Android系统大于等于API16，使用setBackground
            view.setBackground(new BitmapDrawable(context.getResources(), overlay));
        } else {
            //Android系统小于API16，使用setBackground
            view.setBackgroundDrawable(new BitmapDrawable(context.getResources(), overlay));
        }
    }
    //endregion

    //region 用来缩放图片 Zoom(Bitmap bitmap, float x, float y)
    public static Bitmap Zoom(Bitmap bitmap, float x, float y) {
        //图片的宽和高
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();

        //原图片和指定图片宽高比（缩放率），指定/原
        float sx = x / width;
        float sy = y / height;
        float scale = sx > sy ? sx : sy;

        //缩放图片动作
        Matrix mtr = new Matrix();
        mtr.postScale(scale, scale);

        //创建新的图片
        Bitmap bm = Bitmap.createBitmap(bitmap, 0, 0, width, height, mtr, true);
        return bm;
    }
    //endregion

    //region 改变图片颜色 setBitmapColor(Activity activity,int drawable,float colorRed,float colorGreen,float colorBlue,float colorTransparency)
    public static Bitmap setBitmapColor(Activity activity,int drawable,float colorRed,float colorGreen,float colorBlue,float colorTransparency) {
        Bitmap baseBitmap = BitmapFactory.decodeResource(activity.getResources(), drawable);
        // 获取一个与baseBitmap大小一致的可编辑的空图片
        Bitmap afterBitmap = Bitmap.createBitmap(baseBitmap.getWidth(),
        baseBitmap.getHeight(), baseBitmap.getConfig());
        Canvas canvas = new Canvas(afterBitmap);
        Paint paint = new Paint();
        float[] src = new float[]{colorRed, 0, 0, 0, 0,
                0, colorGreen, 0, 0, 0,
                0, 0, colorBlue, 0, 0,
                0, 0, 0, colorTransparency, 0};
        // 定义ColorMatrix，并指定RGBA矩阵
        ColorMatrix colorMatrix = new ColorMatrix();
        colorMatrix.set(src);
        // 设置Paint的颜色
        paint.setColorFilter(new ColorMatrixColorFilter(src));
        // 通过指定了RGBA矩阵的Paint把原图画到空白图片上
        canvas.drawBitmap(baseBitmap, new Matrix(), paint);
        return afterBitmap;
    };
    //endregion

    //region 获得网络的类型 getCurrentNetworkType
    private static final int NETWORK_TYPE_UNAVAILABLE = -1;
    // private static final int NETWORK_TYPE_MOBILE = -100;
    private static final int NETWORK_TYPE_WIFI = -101;

    private static final int NETWORK_CLASS_WIFI = -101;
    private static final int NETWORK_CLASS_UNAVAILABLE = -1;
    /** Unknown network class. */
    private static final int NETWORK_CLASS_UNKNOWN = 0;
    /** Class of broadly defined "2G" networks. */
    private static final int NETWORK_CLASS_2_G = 1;
    /** Class of broadly defined "3G" networks. */
    private static final int NETWORK_CLASS_3_G = 2;
    /** Class of broadly defined "4G" networks. */
    private static final int NETWORK_CLASS_4_G = 3;

    // 适配低版本手机
    /** Network type is unknown */
    public static final int NETWORK_TYPE_UNKNOWN = 0;
    /** Current network is GPRS */
    public static final int NETWORK_TYPE_GPRS = 1;
    /** Current network is EDGE */
    public static final int NETWORK_TYPE_EDGE = 2;
    /** Current network is UMTS */
    public static final int NETWORK_TYPE_UMTS = 3;
    /** Current network is CDMA: Either IS95A or IS95B */
    public static final int NETWORK_TYPE_CDMA = 4;
    /** Current network is EVDO revision 0 */
    public static final int NETWORK_TYPE_EVDO_0 = 5;
    /** Current network is EVDO revision A */
    public static final int NETWORK_TYPE_EVDO_A = 6;
    /** Current network is 1xRTT */
    public static final int NETWORK_TYPE_1xRTT = 7;
    /** Current network is HSDPA */
    public static final int NETWORK_TYPE_HSDPA = 8;
    /** Current network is HSUPA */
    public static final int NETWORK_TYPE_HSUPA = 9;
    /** Current network is HSPA */
    public static final int NETWORK_TYPE_HSPA = 10;
    /** Current network is iDen */
    public static final int NETWORK_TYPE_IDEN = 11;
    /** Current network is EVDO revision B */
    public static final int NETWORK_TYPE_EVDO_B = 12;
    /** Current network is LTE */
    public static final int NETWORK_TYPE_LTE = 13;
    /** Current network is eHRPD */
    public static final int NETWORK_TYPE_EHRPD = 14;
    /** Current network is HSPA+ */
    public static final int NETWORK_TYPE_HSPAP = 15;

    public static String getCurrentNetworkType(Context context) {
        int networkClass = getNetworkClass(context);
        String type = "未知";
        switch (networkClass) {
            case NETWORK_CLASS_UNAVAILABLE:
                type = "无";
                break;
            case NETWORK_CLASS_WIFI:
                type = "Wi-Fi";
                break;
            case NETWORK_CLASS_2_G:
                type = "2G";
                break;
            case NETWORK_CLASS_3_G:
                type = "3G";
                break;
            case NETWORK_CLASS_4_G:
                type = "4G";
                break;
            case NETWORK_CLASS_UNKNOWN:
                type = "未知";
                break;
        }
        return type;
    }

    private static int getNetworkClass(Context context) {
        int networkType = NETWORK_TYPE_UNKNOWN;
        try {
            final NetworkInfo network = ((ConnectivityManager)context
                    .getSystemService(Context.CONNECTIVITY_SERVICE))
                    .getActiveNetworkInfo();
            if (network != null && network.isAvailable()
                    && network.isConnected()) {
                int type = network.getType();
                if (type == ConnectivityManager.TYPE_WIFI) {
                    networkType = NETWORK_TYPE_WIFI;
                } else if (type == ConnectivityManager.TYPE_MOBILE) {
                    TelephonyManager telephonyManager = (TelephonyManager) context.
                            getSystemService(Context.TELEPHONY_SERVICE);
                    networkType = telephonyManager.getNetworkType();
                }
            } else {
                networkType = NETWORK_TYPE_UNAVAILABLE;
            }

        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return getNetworkClassByType(networkType);

    }

    private static int getNetworkClassByType(int networkType) {
        switch (networkType) {
            case NETWORK_TYPE_UNAVAILABLE:
                return NETWORK_CLASS_UNAVAILABLE;
            case NETWORK_TYPE_WIFI:
                return NETWORK_CLASS_WIFI;
            case NETWORK_TYPE_GPRS:
            case NETWORK_TYPE_EDGE:
            case NETWORK_TYPE_CDMA:
            case NETWORK_TYPE_1xRTT:
            case NETWORK_TYPE_IDEN:
                return NETWORK_CLASS_2_G;
            case NETWORK_TYPE_UMTS:
            case NETWORK_TYPE_EVDO_0:
            case NETWORK_TYPE_EVDO_A:
            case NETWORK_TYPE_HSDPA:
            case NETWORK_TYPE_HSUPA:
            case NETWORK_TYPE_HSPA:
            case NETWORK_TYPE_EVDO_B:
            case NETWORK_TYPE_EHRPD:
            case NETWORK_TYPE_HSPAP:
                return NETWORK_CLASS_3_G;
            case NETWORK_TYPE_LTE:
                return NETWORK_CLASS_4_G;
            default:
                return NETWORK_CLASS_UNKNOWN;
        }
    }
    //endregion

    //region 获得应用网速
    public static long getNetWorkFlow(Context context){
        int uid = context.getApplicationInfo().uid;
        long rx = TrafficStats.getUidRxBytes(uid);
        long tx = TrafficStats.getUidTxBytes(uid);
        if(rx<0&&tx<0){
            return 0;
        }else{
            return (rx+tx);
        }
    }
    //endregion

    /* 检测应用是否第一次打开 */
    public static boolean getFirstStart(Context context)
    {
        SharedPreferences sf = context.getSharedPreferences(APP_SHARENAME, Context.MODE_PRIVATE);
        return sf.getBoolean(IS_FIRSTSTART, true);
    }

    public static void setFirstStart(Context context,boolean firstStart)
    {
        SharedPreferences sf = context.getSharedPreferences(APP_SHARENAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sf.edit();
        editor.putBoolean(IS_FIRSTSTART, firstStart);
        editor.commit();
    }

    //region 获打包取渠道号
    public static String getMetaInt(Context con,String name){
        ApplicationInfo ai = null;
        try {
            ai = con.getPackageManager().getApplicationInfo(con.getPackageName(), PackageManager.GET_META_DATA);
        }catch (PackageManager.NameNotFoundException e){
            e.printStackTrace();
        }
        Bundle bundle = ai.metaData;
        return bundle.getString(name);
    }
    //endregion

    public static boolean checkEmail(String email) {
        boolean flag = false;
        try {
            String check = "^([a-z0-9A-Z]+[-|_|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
            Pattern regex = Pattern.compile(check);
            Matcher matcher = regex.matcher(email);
            flag = matcher.matches();
        } catch (Exception e) {
            flag = false;
        }
        return flag;
    }

    public static boolean checkMobileNumber(String mobileNumber) {
        boolean flag = false;
        try {
            // Pattern regex = Pattern.compile("^(((13[0-9])|(15([0-3]|[5-9]))|(18[0,5-9]))\\d{8})|(0\\d{2}-\\d{8})|(0\\d{3}-\\d{7})$");
            Pattern regex = Pattern.compile("^1[345789]\\d{9}$");
            Matcher matcher = regex.matcher(mobileNumber);
            flag = matcher.matches();
        } catch (Exception e) {
            e.printStackTrace();
            flag = false;

        }
        return flag;
    }

    public static boolean IsIDcard(String str) {
        boolean flag = false;
        try {
            String strRegex = "(^\\d{18}$)|(^\\d{15}$)";
            Pattern regex = Pattern.compile(strRegex);
            Matcher matcher = regex.matcher(str);
            flag = matcher.matches();
        } catch (Exception e) {
            e.printStackTrace();
            flag = false;

        }
        return flag;
    }

    public static Uri getImageContentUri(Context context, File imageFile)
    {
        String filePath = imageFile.getAbsolutePath();
        Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new String[] { MediaStore.Images.Media._ID }, MediaStore.Images.Media.DATA + "=? ", new String[] { filePath }, null);

        if (cursor != null && cursor.moveToFirst())
        {
            int id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID));
            Uri baseUri = Uri.parse("content://media/external/images/media");
            return Uri.withAppendedPath(baseUri, "" + id);
        }
        else
        {
            if (imageFile.exists())
            {
                ContentValues values = new ContentValues();
                values.put(MediaStore.Images.Media.DATA, filePath);
                return context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            }
            else
            {
                return null;
            }
        }
    }

}
